import DropDownArrow from '@/components/DropDownArrow';
import { View } from '@tarojs/components';
import classNames from 'classnames';
import React, { useCallback, useEffect, useState } from 'react';
import './dropDownSelect.scss';

/**
 * @param selectFunc selectFunc会返回选中的列表的index数组
 * @param title title不会作为选项,不传这个参数时组件默认显示列表第一项
 */
function DropDownSelect({
  className = '',
  isOpen = false,
  setOpenStatus,
  selectList,
  title,
  titleClassName = '',
  singleSelect = false,
  selectFunc,
  defaultSelect,
  disabled = false,
  disableUnSelect = false,
}) {
  const [selectedArray, setSelectedArray] = useState([]);

  useEffect(() => {
    if (defaultSelect || defaultSelect === 0) {
      if (Array.isArray(defaultSelect)) {
        setSelectedArray([...defaultSelect.filter((index) => index !== -1)]);
      } else {
        if (defaultSelect === -1) {
          setSelectedArray([]);
        } else {
          setSelectedArray([defaultSelect]);
        }
      }
    } else {
      if (selectedArray.length === 0) return;
      setSelectedArray([]);
    }
  }, [defaultSelect]);

  const selectItem = useCallback(
    (e) => {
      let index = Number(e.target.dataset.index ?? e.target['data-index']);
      if (singleSelect) {
        if (selectedArray[0] === index) {
          if (!disableUnSelect) {
            selectedArray.pop();
          }
        } else {
          selectedArray[0] = index;
        }
      } else {
        let arrayIndex = selectedArray.findIndex((selectedIndex) => selectedIndex === index);
        if (arrayIndex === -1) {
          selectedArray.push(index);
        } else {
          selectedArray.splice(arrayIndex, 1);
        }
      }
      selectFunc && selectFunc(selectedArray, setSelectedArray);
    },
    [selectFunc, selectedArray],
  );

  let displayText = '';
  if (selectedArray.length !== 0) {
    const arr = [];
    selectedArray.forEach((index) => {
      if (Object.prototype.toString.call(selectList[index]) === '[object Object]') {
        if (selectList[index].text !== '') {
          arr.push(selectList[index].text);
        }
      }
    });
    if (
      arr.length == 1 &&
      Object.prototype.toString.call(selectList[0].text) === '[object Object]' &&
      singleSelect
    ) {
      displayText = arr[0];
    } else {
      displayText = arr.join(';');
    }
  }
  if (displayText === '') {
    displayText = title;
    if (title === undefined) {
      displayText = selectList[0].text;
    }
  }

  return (
    <View className={['dropdownSelect', className].join(' ')}>
      <View className="sel" onClick={() => setOpenStatus(!isOpen)}>
        <View
          className={classNames('selText', {
            'black customePageStyle': isOpen || displayText != title,
            [titleClassName]: !!titleClassName,
          })}
        >
          {displayText}
        </View>
        <DropDownArrow director={isOpen ? 'up' : 'down'} active={isOpen || displayText != title} />
      </View>
      {isOpen && selectList.length > 0 && (
        <>
          <View className="listBox" onClick={(e) => !disabled && selectItem(e)}>
            {selectList.map((item, index) => {
              return (
                <View
                  className={classNames('item', {
                    'active customePageStyle': selectedArray.includes(index),
                  })}
                  data-index={index}
                  key={'_' + index}
                >
                  {item.text}
                </View>
              );
            })}
          </View>
        </>
      )}
    </View>
  );
}
export default DropDownSelect;
